package org.example.core.elasticsearch.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.common.utils.ResponseUtil;
import org.example.core.elasticsearch.document.GoodsDocument;
import org.example.core.elasticsearch.service.ElasticSearchService;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/elasticsearch")
public class ElasticSearchController {

    ElasticSearchService elasticSearchService;

    public ElasticSearchController(ElasticSearchService elasticSearchService) {
        this.elasticSearchService = elasticSearchService;
    }

    @PostMapping("/post")
    public Object post(@RequestBody GoodsDocument document){

        try {
            elasticSearchService.save(document);
        } catch (IOException e) {
            log.error(e.getMessage(), e.getCause());
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok();
    }

    @GetMapping("/get")
    public Object get(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") Integer from,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "") String preTags,
            @RequestParam(defaultValue = "") String postTags
    ) throws IOException {

        ArrayList<Map<String, Object>> query = elasticSearchService.query(keyword, from, size, preTags, postTags);

        return ResponseUtil.ok(query);
    }
}
